/*
 * @Author: taoyuqing
 * @Date: 2023-01-09 23:12:47
 * @Description: 历史页面
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:spree/widgets/vip_rectangle_box.dart';

import '../../utils/api.dart';
import 'history_table.dart';

class OrderHistoryPage extends StatefulWidget {
  OrderHistoryPage({Key? key}) : super(key: key);

  @override
  State<OrderHistoryPage> createState() => _OrderHistoryPageState();
}

class _OrderHistoryPageState extends State<OrderHistoryPage> {
  String _startTime = '';
  String _endTime = '';
  String _type = '';
  List _gamesType = [
    {'label': 'DICE', 'isCheck': true},
    {'label': 'DOUBLE', 'isCheck': false},
    {'label': 'CRASH', 'isCheck': false},
    {'label': 'MINES', 'isCheck': false},
  ]; //局部刷新
  late List<Map<dynamic, dynamic>> records = [];
  int countNum = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('wallet history'),
      ),
      body: CommonContainer(
        child: ListView(
          padding: EdgeInsets.only(top: 20),
          children: [
            VipRectangleBox(
              padding: EdgeInsets.all(12),
              color: Color(0xFF331F69),
              onTap: () async {
                DateTime dateTime = await _showDatePicker();
                setState(() {
                  _startTime =
                      '${dateTime.year}-${dateTime.month}-${dateTime.day}';
                });
              },
              child: Row(
                children: [
                  Icon(Icons.date_range, color: Color(0xFFB0AFEC)),
                  Container(
                    margin: EdgeInsets.only(left: 12),
                    child: Text(
                      'start time:   $_startTime',
                      style: TextStyle(color: Color(0xFFB0AFEC)),
                    ),
                  ),
                ],
              ),
            ),
            VipRectangleBox(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.all(12),
              color: Color(0xFF331F69),
              onTap: () async {
                DateTime dateTime = await _showDatePicker();
                setState(() {
                  _endTime =
                      '${dateTime.year}-${dateTime.month}-${dateTime.day}';
                });
              },
              child: Row(
                children: [
                  Icon(Icons.date_range, color: Color(0xFFB0AFEC)),
                  Container(
                    margin: EdgeInsets.only(left: 12),
                    child: Text(
                      'end time:   $_endTime',
                      style: TextStyle(color: Color(0xFFB0AFEC)),
                    ),
                  )
                ],
              ),
            ),
            VipRectangleBox(
              margin: EdgeInsets.only(top: 20),
              color: Color(0xFF331F69),
              child: ExpansionTile(
                initiallyExpanded: false,
                collapsedIconColor: Colors.white,
                iconColor: Colors.white,
                title: Text(
                  'Game Type',
                  style: TextStyle(color: Colors.white),
                ),
                children: _createExpansionPanel(_gamesType),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              height: 50,
              child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Color(0xFF7E68FF)),
                  ),
                  onPressed: () {
                    checkDate();
                    searchData();
                  },
                  child: Text('Search')),
            ),
            HistoryTable(
              data: records,
              firstKey: 'recordNo',
              dataKeys: ['recordNo', 'depositAmount', 'recordTime'],
              header: ['订单号', '交易金额', '交易时间'],
              dataLength: double.parse(countNum.toString()),
              cellWidth: 40,
            )
          ],
        ),
      ),
    );
  }

  Future<void> searchData() async {
    Map params = {'startTime': _startTime, 'endTime': _endTime};
    dynamic depositRecords = await Api.depositRecords(params);
    int count = depositRecords['data']['count'];
    countNum = count;
    List data = depositRecords['data']['data'];
    print(data);
    setState(() {
      records = List<Map<dynamic, dynamic>>.from(data);
    });
  }

  void checkDate() {
    var nowTime = DateTime.now();
    if (_startTime == '' || _startTime == null) {
      _startTime = nowTime.year.toString() +
          "-" +
          nowTime.month.toString() +
          "-" +
          nowTime.day.toString();
    }

    if (_endTime == '' || _endTime == null) {
      _endTime = nowTime.year.toString() +
          "-" +
          nowTime.month.toString() +
          "-" +
          nowTime.day.toString();
    }

    if (_startTime != "" && _endTime != "") {
      //需要判断时间是否合适
      var startDate = DateFormat("yyyy-MM-dd").parse(_startTime);
      var endDate = DateFormat("yyyy-MM-dd").parse(_endTime);
      if (endDate.isBefore(startDate)) {
        EasyLoading.showToast("结束日期必须比开始日期大");
        return;
      }
    }
  }

  List<Widget> _createExpansionPanel(List valueNotifier) {
    List<Widget> tiles = valueNotifier.asMap().keys.map((i) {
      return GestureDetector(
        onTap: () {
          setState(() {
            for (var i = 0; i < valueNotifier.length; i++) {
              valueNotifier[i]['isCheck'] = false;
            }
            valueNotifier[i]['isCheck'] = !valueNotifier[i]['isCheck'];
          });
        },
        child: ListTile(
          trailing: valueNotifier[i]['isCheck']
              ? Icon(
                  Icons.check,
                  color: Color(0xffB0AFEC),
                )
              : null,
          title: Text(
            valueNotifier[i]['label'],
            style: TextStyle(color: Color(0xffB0AFEC)),
          ),
        ),
      );
    }).toList();

    return tiles;
  }

  Future _showDatePicker() {
    Completer<DateTime> c = Completer();
    DatePicker.showDatePicker(
      context,
      showTitleActions: true,
      currentTime: DateTime.now(),
      locale: LocaleType.zh,
      minTime: DateTime(2018, 3, 5),
      maxTime: DateTime.now(),
      onConfirm: (date) {
        c.complete(date);
      },
    );
    return c.future;
  }
}
